package com.zouxw.utils.json.utils;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.util.HashSet;
import java.util.Set;

/**
 * 树节点展开状态管理工具类
 * 负责保存和恢复树节点的展开状态
 * 
 * @author zouxw
 * @version 1.0
 */
public class TreeExpansionStateManager {
    
    // ==================== 实例变量 ====================
    /** 展开的节点路径集合 */
    private Set<String> expandedPaths;
    
    /** 当前选中的节点路径 */
    private String selectedPath;
    
    // ==================== 构造函数 ====================
    
    /**
     * 构造函数
     */
    public TreeExpansionStateManager() {
        this.expandedPaths = new HashSet<>();
        this.selectedPath = null;
    }
    
    // ==================== 公共方法 ====================
    
    /**
     * 保存树的展开状态
     * 
     * @param tree 树组件
     */
    public void saveExpansionState(JTree tree) {
        if (tree == null) {
            return;
        }
        
        expandedPaths.clear();
        
        // 保存所有展开的节点路径
        for (int i = 0; i < tree.getRowCount(); i++) {
            TreePath path = tree.getPathForRow(i);
            if (tree.isExpanded(path)) {
                String pathString = getPathString(path);
                expandedPaths.add(pathString);
            }
        }
        
        // 保存当前选中的节点路径
        TreePath selectedTreePath = tree.getSelectionPath();
        if (selectedTreePath != null) {
            selectedPath = getPathString(selectedTreePath);
        } else {
            selectedPath = null;
        }
        
        System.out.println("保存展开状态: " + expandedPaths.size() + " 个展开节点");
    }
    
    /**
     * 恢复树的展开状态
     * 
     * @param tree 树组件
     */
    public void restoreExpansionState(JTree tree) {
        if (tree == null || expandedPaths.isEmpty()) {
            return;
        }
        
        System.out.println("恢复展开状态: " + expandedPaths.size() + " 个展开节点");
        
        // 恢复展开状态
        for (int i = 0; i < tree.getRowCount(); i++) {
            TreePath path = tree.getPathForRow(i);
            String pathString = getPathString(path);
            
            if (expandedPaths.contains(pathString)) {
                tree.expandPath(path);
            }
        }
        
        // 恢复选中状态并滚动到该位置
        if (selectedPath != null) {
            TreePath targetPath = findPathByString(tree, selectedPath);
            if (targetPath != null) {
                tree.setSelectionPath(targetPath);
                tree.scrollPathToVisible(targetPath);
                System.out.println("恢复选中状态: " + selectedPath);
            }
        }
    }
    
    /**
     * 根据路径字符串查找对应的TreePath
     * 
     * @param tree 树组件
     * @param pathString 路径字符串
     * @return 对应的TreePath，如果找不到返回null
     */
    private TreePath findPathByString(JTree tree, String pathString) {
        if (tree == null || pathString == null) {
            return null;
        }
        
        // 遍历所有行，查找匹配的路径
        for (int i = 0; i < tree.getRowCount(); i++) {
            TreePath path = tree.getPathForRow(i);
            String currentPathString = getPathString(path);
            
            // 精确匹配
            if (pathString.equals(currentPathString)) {
                return path;
            }
            
            // 模糊匹配：如果保存的路径是当前路径的前缀，也认为匹配
            if (currentPathString.startsWith(pathString + "/")) {
                return path;
            }
        }
        
        return null;
    }
    
    /**
     * 获取路径的字符串表示
     * 
     * @param path 树路径
     * @return 路径字符串
     */
    private String getPathString(TreePath path) {
        if (path == null) {
            return "";
        }
        
        StringBuilder pathString = new StringBuilder();
        Object[] pathArray = path.getPath();
        
        for (int i = 0; i < pathArray.length; i++) {
            if (i > 0) {
                pathString.append("/");
            }
            
            Object component = pathArray[i];
            if (component instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) component;
                pathString.append(node.getUserObject().toString());
            } else {
                pathString.append(component.toString());
            }
        }
        
        return pathString.toString();
    }
    
    /**
     * 清空保存的状态
     */
    public void clear() {
        expandedPaths.clear();
        selectedPath = null;
    }
    
    /**
     * 获取展开节点数量
     * 
     * @return 展开节点数量
     */
    public int getExpandedNodeCount() {
        return expandedPaths.size();
    }
    
    /**
     * 是否有保存的状态
     * 
     * @return 是否有保存的状态
     */
    public boolean hasState() {
        return !expandedPaths.isEmpty() || selectedPath != null;
    }
}
